using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Park.Net.Model;
using System.ComponentModel.DataAnnotations;
using Park.Net.EFCoreEnv;
using Park.Net.IService;

namespace Park.Net.ParkWebAPI.Controllers
{
    [ApiController]
    [Route("api/login")]
    public class LoginController : ControllerBase
    {

        private readonly IBaseServices<Owner> OwnerServers;

        public LoginController(IBaseServices<Owner> CarParkService)
        {
            OwnerServers = CarParkService;
        }
        

        [HttpGet]
        public IActionResult Login(string Phone, string password)
        {

            // 验证手机号和密码是否匹配
            var owner = OwnerServers.FindOneAsync(o => o.Phone == Phone && o.Password == password);
            if (owner == null)
            {
                return BadRequest("未注册");
            }

            // 登录成功，返回业主信息
            return Ok(owner);
        }


        [HttpPost]
        [Route("api/register")]
        public IActionResult Register(Owner ownerRegister)
        {
            // 判断参数是否有效
            if (ownerRegister == null || !ModelState.IsValid)
            {
                return BadRequest("Invalid parameter");
            }

            // 判断手机号是否已被注册
            if (OwnerServers.FindOneAsync(o => o.Phone == ownerRegister.Phone) != null)
            {
                return BadRequest("The phone number has been registered");
            }

            // 创建业主对象并保存到数据库
            // var owner = new Owner
            // {
            //     Name = ownerRegister.Name,
            //     Gender = ownerRegister.Gender,
            //     IDCard = payload.IDCard,
            //     Phone = payload.Phone,
            //     Password = payload.Password,
            //     CarNumber = payload.CarNumber,
            //     Address = payload.Address,
            //     RoomNumber = payload.RoomNumber
            // };
            // _dbContext.Owners.Add(owner);
            // _dbContext.SaveChanges();
            OwnerServers.UpdateAsync(ownerRegister);

            // 注册成功
            return Ok();
        }


    }
}